#include <clang-c/Index.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>

#include "completion.h"
#include "msg_callback.h"

#include "flags-groups.h"
#include <assert.h>

/* This function is intended to help debugging transmition issues, and should 
   not be called in the final release version. */
void __dump_session(const completion_Session *session, FILE *fp)
{
    int i_arg = 0;
    for ( ; i_arg < session->num_args; i_arg++) {
        fprintf(fp, "[%-2d]: %s\n", i_arg, session->cmdline_args[i_arg]);
    }

    fprintf(fp, "filename: %s\n"
            "code:\n%s\n", 
            session->src_filename, session->src_buffer); fflush(fp);
}



int main(int argc, char *argv[])
{
    completion_Session session;
	char *argvs[]={"./clang-complete" "" };

	if ( argc >= 2 )
	  {
		int new_argc;
		char **new_argv;
		const char *file;
		file = find_file();

		struct group_list gl;
		group_list_init( &gl );
		group_list_get_from_file( &gl, file );
		group_list_resolve( &gl );
		group_list_merge( &gl );
		//group_list_show( &gl );
		struct group *grp_max = group_list_match( &gl, argv[ argc-1 ] );
		if ( grp_max )
        {
			group_show( grp_max );
			new_argc = grp_max->merged_argc + argc;
			new_argv = calloc( sizeof(char*), new_argc );
			assert( new_argv );
			int i;
			char **p = new_argv;
			for ( i=0; i<argc-1; i++)
            {
				*p++ = argv[ i ];
            }
			for ( i=0; i<grp_max->merged_argc; i++ )
            {
				*p++ = strdup(grp_max->merged_argv[ i ]);
            }
			*p = argv[ argc-1 ];
        } else {
            new_argc = argc;
            new_argv = argv;
		}
		group_list_destroy( &gl );

		startup_completionSession(new_argc, new_argv, &session);
    } else {
        argc = 2;
        argv = argvs;
        startup_completionSession(argc, argv, &session);
    }

    for ( ; ; ) {
        completion_AcceptRequest(&session, stdin);
    }

    return 0;
}
